package cn.thoughtworks.school.programCenter.services;

import cn.thoughtworks.school.programCenter.entities.Assignment;
import cn.thoughtworks.school.programCenter.entities.AssignmentQuizMark;
import cn.thoughtworks.school.programCenter.exceptions.BusinessException;
import cn.thoughtworks.school.programCenter.repositories.AssignmentQuizMarkRepository;
import cn.thoughtworks.school.programCenter.repositories.AssignmentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class AssignmentQuizMarkService {
    @Autowired
    private AssignmentQuizMarkRepository assignmentQuizMarkRepository;
    @Autowired
    private AssignmentRepository assignmentRepository;

    public AssignmentQuizMark getAssignmentQuizMark(Long assignmentId, Long quizId, Long studentId, Long userId) throws BusinessException {
        if (isBasicQuiz(assignmentId)) {
            return assignmentQuizMarkRepository.findByAssignmentIdAndStudentIdAndOperatorId(assignmentId, studentId, userId)
                    .orElse(new AssignmentQuizMark());
        }
        return assignmentQuizMarkRepository.findByAssignmentIdAndQuizIdAndStudentIdAndOperatorId(assignmentId, quizId, studentId, userId)
                .orElse(new AssignmentQuizMark());
    }

    private boolean isBasicQuiz(Long assignmentId) throws BusinessException {
        Assignment assignment = assignmentRepository.findById(assignmentId)
                .orElseThrow(() -> new BusinessException("Assignment is not exist."));

        return "BASIC_QUIZ".equals(assignment.getType());
    }

    public void editAssignmentQuizMark(AssignmentQuizMark assignmentQuizMark) throws BusinessException {
        AssignmentQuizMark assignmentQuizMarkInfo = assignmentQuizMarkRepository.findById(assignmentQuizMark.getId())
                .orElseThrow(() -> new BusinessException("AssignmentQuizMark is not exist."));
        assignmentQuizMarkInfo.setEvaluate(assignmentQuizMark.getEvaluate());
        assignmentQuizMarkInfo.setRanking(assignmentQuizMark.getRanking());
        assignmentQuizMarkRepository.save(assignmentQuizMarkInfo);
    }

    public AssignmentQuizMark addAssignmentQuizMark(Long userId, AssignmentQuizMark assignmentQuizMark) throws BusinessException {
        if (isBasicQuiz(assignmentQuizMark.getAssignmentId())) {
            assignmentQuizMark.setQuizId(null);
        }
        assignmentQuizMark.setOperatorId(userId);
        assignmentQuizMark.setCreateTime(new Date());
        return assignmentQuizMarkRepository.save(assignmentQuizMark);
    }
}